package com.qymerge.manage.system.controller;

import com.qymerge.manage.base.enums.ActiveTypes;
import com.qymerge.manage.core.bean.ActionResultRO;
import com.qymerge.manage.core.bean.ParamValue;
import com.qymerge.manage.core.constant.ParamKey;
import com.qymerge.manage.core.controller.BaseController;
import com.qymerge.manage.core.enums.StatusTypes;
import com.qymerge.manage.core.utils.GsonUtil;
import com.qymerge.manage.core.utils.PrintCodeUtils;
import com.qymerge.manage.core.utils.RequestCheckUtils;
import com.qymerge.manage.system.dto.SysMenuDTO;
import com.qymerge.manage.system.dto.SysUserDTO;
import com.qymerge.manage.system.dto.SysUserSnapDTO;
import com.qymerge.manage.system.dto.SysUserSnapshotDTO;
import com.qymerge.manage.system.ro.SysUserRO;
import com.qymerge.manage.system.service.IUserService;
import com.qymerge.manage.system.service.IWelcomeService;
import com.google.common.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *<p>Title: UserController</p>
 *<p>Description: 用户登录类</p>
 *
 *@Author cong.zhang
 *@Version 1.0.0
 *@Date 2020/8/3
 *@Time 20:24
 */
@Controller
@RequestMapping(value = "user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IWelcomeService welcomeService;

    /**
     * 登录（后台管理系统）
     *
     * @return
     */
    @RequestMapping(value = "login")
    public void login(HttpServletRequest request, HttpServletResponse response,
                      @RequestHeader(value = "x-cert-uid", required = false) String accountId,

                      @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                      @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        SysUserRO userRO = paramValue.getData();

        RequestCheckUtils.checkNotEmpty(userRO.getPhone(), "手机号不能为空！");
        RequestCheckUtils.checkNotEmpty(userRO.getPassword(), "密码不能为空");

        // 初始化
//        if (!welcomeService.isInit()) {
////            welcomeService.initBaseInfo();
////        }

        SysUserSnapshotDTO snapshotDTO = userService.checkUserSnapshot(userRO);
        if (snapshotDTO != null) {

            if(snapshotDTO.getStatus() == null || snapshotDTO.getStatus() == StatusTypes.OffLine.getStatus()){
                PrintCodeUtils.printError(response, "当前登录用户，已经被禁止登录系统，请联系管理员处理...", callback);
            }

            PrintCodeUtils.printSuccess(response, snapshotDTO, callback);
        } else {
            PrintCodeUtils.printError(response, "用户名或密码错误!", callback);
        }

    }

    /**
     * 登录（小程序接口API）
     *
     * @return
     */
    @RequestMapping(value = "/m/login")
    public void login(HttpServletRequest request, HttpServletResponse response,

                      @RequestBody SysUserRO userRO,
                      @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {

        RequestCheckUtils.checkNotEmpty(userRO.getPhone(), "手机号不能为空！");
        RequestCheckUtils.checkNotEmpty(userRO.getPassword(), "密码不能为空");

        SysUserSnapshotDTO snapshotDTO = userService.checkUserSnapshot(userRO);
        if (snapshotDTO != null) {

            if(snapshotDTO.getStatus() == StatusTypes.OffLine.getStatus()){
                PrintCodeUtils.printError(response, "当前登录用户，已经被禁止登录系统，请联系管理员处理...", callback);
            }

            PrintCodeUtils.printSuccess(response, snapshotDTO, callback);
        } else {
            PrintCodeUtils.printError(response, "手机号或密码错误!", callback);
        }

    }

    /**
     * 后台管理系统-获取用户信息
     *
     * @param
     * @param callback
     * @return
     */
    @RequestMapping(value = "/m/info")
    public void getSysUser(HttpServletRequest request, HttpServletResponse response,

                           @RequestBody SysUserRO userRO,
                           @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {

        RequestCheckUtils.checkNotEmpty(userRO.getId(), "用户ID必须！");

        SysUserSnapDTO data = userService.getSysUser(userRO);
        PrintCodeUtils.printSuccess(response, data, callback);
    }

    /**
     * 修改密码
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updatePwd")
    public void updatePwd(HttpServletRequest request, HttpServletResponse response,

                          @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                          @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserDTO>>() {
        }.getType());
        SysUserDTO user = paramValue.getData();

        // 验证原密码
        SysUserRO sysUser = userService.checkPassword(user);
        if (sysUser != null) {
            if (userService.editUserPwd(user)) {
                PrintCodeUtils.print(response, new ActionResultRO(1,"密码修改成功"), callback);
            } else {
                PrintCodeUtils.print(response, new ActionResultRO(0,"密码修改失败，请联系管理员"), callback);
            }
        } else {
            PrintCodeUtils.printError(response, "原密码不正确!");
        }
    }

    /**
     * 修改密码
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/resetPwd")
    public void resetUpdatePwd(HttpServletRequest request, HttpServletResponse response,

                          @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                          @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserDTO>>() {
        }.getType());
        SysUserDTO user = paramValue.getData();

        ActionResultRO actionResultRO = userService.resetUserPwd(user);
        PrintCodeUtils.print(response, actionResultRO, callback);
    }

    /**
     * 获取用户可操作菜单
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getMenus")
    public void getMenus(HttpServletRequest request, HttpServletResponse response,

                         @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                         @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserDTO>>() {
        }.getType());
        SysUserDTO userDto = paramValue.getData();

        Long userDtoId = userDto.getId();
        String token = userDto.getToken();
        SysUserRO sysUserRO = new SysUserRO();
        sysUserRO.setId(userDtoId);
        SysUserSnapDTO sysUser = userService.getSysUser(sysUserRO);

        List<SysMenuDTO> menuDtos = null;
        if (sysUser != null && sysUser.getToken().equals(token)) {
            menuDtos = userService.getMenuByUser(userDtoId);
        }
//        RequestCheckUtils.checkNotEmpty(userDtoId, "ID必须");

        PrintCodeUtils.printSuccess(response, userService.formatMenuJson(menuDtos), callback);
    }

    /**
     * 验证用户是否有权限访问指定页面
     * 获取用户id和要访问的html页面，然后和用户可访问菜单列表匹配，存在则可以访问，否则无权访问
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkUserRole")
    public void checkUserRole(HttpServletResponse response, HttpServletRequest request) {
        long id = Long.valueOf(request.getParameter("id"));
        String pageUlr = request.getParameter("page_url");
        List<SysMenuDTO> menuList = userService.getMenuByUser(id);
        boolean flag = false;
        for (SysMenuDTO menu : menuList) {
            if (menu.getMenu_path().contains(pageUlr)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            PrintCodeUtils.printSuccess(response, "验证通过");
        } else {
            PrintCodeUtils.printError(response, "对不起，您无权访问");
        }
    }

}
